/**
 * 共用JS方法
 */

$(function() {
	if (!Array.prototype.indexOf)
	{
	  Array.prototype.indexOf = function(elt /*, from*/)
	  {
	    var len = this.length >>> 0;

	    var from = Number(arguments[1]) || 0;
	    from = (from < 0)
	         ? Math.ceil(from)
	         : Math.floor(from);
	    if (from < 0)
	      from += len;

	    for (; from < len; from++)
	    {
	      if (from in this &&
	          this[from] === elt)
	        return from;
	    }
	    return -1;
	  };
	}
})
  /**
   * [indexOfArr description]
   * @param  {Array} arr 需要校验的数组
   * @param  {string} str 需要校验的字符串
   * @return {number}     返回 [-1] 表示未找到，其它则表示字符串所在数组位置
   */
	function indexOfArr(arr, str) {
		var len = arr.length;
		var pos = -1;

		if (len === 0) return -1;
		for(var i = 0; i < len; i++){
			if(typeof arr[i] == "object") {

				for (v in arr[i]) {

					if(arr[i].id === str) {
						pos = i;
						break;
					}
				}
			}
			else {
				pos = arr.indexOf(str);
			}
		}
		return pos;
	}

	/**
	 * [blurUpdateSku 处理输入内容后判断内容是否重复]
	 * @param  {array} arr    需要处理数组
	 * @param  {array} addObj 添加内容
	 * @param {string} oldtext 已存在内容
	 * @param {number} type 状态 1新增, 2编辑
	 * @return {array} 返回处理后数组
	 */
	function blurUpdateSku (arr, addObj, oldtext, type) {
		var _arr = arr;
		var _addObj = addObj;
		var _oldtext = oldtext;
		var _type = type;

		var _len = _arr.length; //数组长度
		var _pos; //该元素位置所在数组位置

		if(_len === 0) {
			_arr.push(_addObj);
			return _arr;
		}

		for (var i = 0; i < _len; i++) {
			if(_arr[i].id === _addObj.id) {
				_pos = i;
				break;
			}
			else {
				if(_arr[i].name === _oldtext) {
					_pos = i;
				}
				else {
					_pos = -1;
				}
			}
		}

		if(_pos === -1) {
			if(_oldtext) {
				for (var i = 0; i < _len; i++) {
					if(_arr[i].id === _oldtext || _arr[i].name === _oldtext) {
						_addObj.id = _addObj.id;
						_addObj.name = _addObj.name;

						_arr.splice(i, 1, _addObj);
					}
					else {
						var _posId = indexOfArr(_arr, _addObj.id); //返回新内容是否已存在
						if(_posId === -1) {
							_arr.push(_addObj);
						}
					}
				}
			}
			else {
				_arr.push(_addObj);
			}
		}
		else {
			if(_type === 1) {
				addObj.id = addObj.name;
			}
			_arr.splice(_pos, 1, addObj);
		}

		return _arr;
	}


	/**
	 * [jointStr description]
	 * @param {array} attribute 属性栏目
	 * @return {array} 返回所以SKU组合拼接后数组
	 */
	function jointStr(attribute) {
		var _arrIdStr = [[]]; //存组合后字符串
		var _arrNameStr = [[]]; //存组合后字符串
		var imgObj = []; //存储当前组合图片
		var skuLen = []; //商品各已选属性长度
		var len = attribute.length;

		for (var i = 0; i < len; i++) {
			var tarrId = [];
			var tarrName = []

			if(attribute[i].length > 0) {
				skuLen.push(attribute[i].length);
			}

			if(skuLen.length === 1) {
				for (var p = 0; p < attribute[i].length; p++) {

					tarrId.push(attribute[i][p].id);
					tarrName.push(attribute[i][p].name);

					if(tarrId.length !=0 && tarrName.length !=0) {
						_arrIdStr = tarrId;
						_arrNameStr = tarrName;
					}

				}
			} else if(skuLen.length > 1) {
				for (var j = 0; j < _arrIdStr.length; j++) {
					for (var k = 0; k < attribute[i].length; k++) {
						tarrId.push(_arrIdStr[j]+'|'+attribute[i][k].id);
						tarrName.push(_arrNameStr[j]+' | '+attribute[i][k].name);
					}
				}

				if(tarrId.length !=0 && tarrName.length !=0) {
					_arrIdStr = tarrId;
					_arrNameStr = tarrName;
				}

			}
			else {
				_arrIdStr = [];
				_arrNameStr = [];
			}
		}

		return {attrIdStr: _arrIdStr, attrNameStr: _arrNameStr};
	}

	// 主图鼠标移入若有图片则显示左右移动按钮
	$(document).on('mouseover', '.img-upload', function() {
		var _v = $(this).find('.uploadimage-preview img').attr('src');

		if(_v != "") {
			$(this).find('.upload-move i').css({display: "inline-block"});
			$(this).find('.round-delete').css({display: "inline-block"});
			$(this).css("overflow", "visible");
		}
	});

	// 主图鼠标移出隐藏左右移动按钮
	$(document).on('mouseout', '.img-upload', function() {
		$(this).find('.upload-move i').css({display: "none"});
		$(this).find('.round-delete').css({display: "none"});
		$(this).css({overflow: "hidden"});
	});

	// 主图左移动
	$(document).on('click', '.upload-move-left', function() {
		var parentDom = $(this).parents('.img-upload');
		var id = parentDom.parent().index(); //当前图片框id
		var _v1 = parentDom.find('.uploadimage-preview img').attr('src'); //自己图片地址
		var _v2 =  $('#master-img li').eq(id-1).find('.uploadimage-preview img').attr('src'); //左边图片地址
		var _hv1 = parentDom.find('input[type=hidden]').val(); //自己hidden 图片地址
		var _hv2 = $('#master-img li').eq(id-1).find('input[type=hidden]').val(); //左边图片hidden 图片地址

		parentDom.find('.uploadimage-preview img').attr('src', _v2);
		parentDom.find('input[type=hidden]').val(_hv2);

		$('#master-img li').eq(id-1).find('.uploadimage-preview img').attr('src', _v1);
		$('#master-img li').eq(id-1).find('input[type=hidden]').val(_hv1);

		$(".img-upload").find('.upload-move i').css({display: "none"});

	});

	//主图右移动
	$(document).on('click', '.upload-move-right', function(){
		var parentDom = $(this).parents('.img-upload');
		var id = parentDom.parent().index(); //当前图片框id
		if(id+1 === $('#master-img li').length ) {
			id = -1;
		}
		var _v1 = parentDom.find('.uploadimage-preview img').attr('src'); //自己图片地址
		var _v2 =  $('#master-img li').eq(id+1).find('.uploadimage-preview img').attr('src'); //右边边图片地址
		var _hv1 = parentDom.find('input[type=hidden]').val(); //自己hidden 图片地址
		var _hv2 = $('#master-img li').eq(id+1).find('input[type=hidden]').val(); //左边图片hidden 图片地址

		parentDom.find('.uploadimage-preview img').attr('src', _v2);
		parentDom.find('input[type=hidden]').val(_hv2);

		$('#master-img li').eq(id+1).find('.uploadimage-preview img').attr('src', _v1);
		$('#master-img li').eq(id+1).find('input[type=hidden]').val(_hv1);

		$(".img-upload").find('.upload-move i').css({display: "none"});

	});

	//主图删除
	$(document).on('click', '#master-img .round-delete', function() {
		var parentDom = $(this).parents('.img-upload');
		var id = parentDom.parent().index(); //当前图片框id

		$('#master-img li').eq(id).find('.uploadimage-preview img').attr('src', '');
		$('#master-img li').eq(id).find('input[type=file]').val('');
		$('#master-img li').eq(id).find('input[type=hidden]').val('');

		if(id === 0) {
			var img2 = $('#master-img li').eq(1).find('.uploadimage-preview img').attr('src');
			var img3 = $('#master-img li').eq(2).find('.uploadimage-preview img').attr('src');
			var img4 = $('#master-img li').eq(3).find('.uploadimage-preview img').attr('src');
			var src1 = '';
			var src2 = '';

			if(img2) {
				src1 = $('#master-img li').eq(1).find('.uploadimage-preview img').attr('src');
				src2 = $('#master-img li').eq(1).find('input[type=hidden]').val();

				$('#master-img li').eq(1).find('.uploadimage-preview img').attr('src', '');
				$('#master-img li').eq(1).find('input[type=file]').val('');
				$('#master-img li').eq(1).find('input[type=hidden]').val('');
			}
			else if (img3) {
				src1 = $('#master-img li').eq(2).find('.uploadimage-preview img').attr('src');
				src2 = $('#master-img li').eq(2).find('input[type=hidden]').val();

				$('#master-img li').eq(2).find('.uploadimage-preview img').attr('src', '');
				$('#master-img li').eq(2).find('input[type=file]').val('');
				$('#master-img li').eq(2).find('input[type=hidden]').val('');

			}
			else if (img4) {
				src1 = $('#master-img li').eq(3).find('.uploadimage-preview img').attr('src');
				src2 = $('#master-img li').eq(3).find('input[type=hidden]').val();

				$('#master-img li').eq(3).find('.uploadimage-preview img').attr('src', '');
				$('#master-img li').eq(3).find('input[type=file]').val('');
				$('#master-img li').eq(3).find('input[type=hidden]').val('');

			}

			$('#master-img li').eq(0).find('.uploadimage-preview img').attr('src', src1);
			$('#master-img li').eq(0).find('input[type=hidden]').val(src2);
		}

		$(".img-upload").find('.upload-move i').css({display: "none"});
	});

	//sku属性列表图片删除
	$(document).on('click', '#attribute-list .round-delete', function() {
		var parentDom = $(this).parents('.img-upload');
		var id = parentDom.parents('tr').index(); //当前图片框id

		$('#attribute-list tr').eq(id).find('.uploadimage-preview img').attr('src', '');
		$('#attribute-list tr').eq(id).find('input[type=file]').val('');
		$('#attribute-list tr').eq(id).find('.img-upload input[type=hidden]').val('');

		$(".img-upload").find('.upload-move i').css({display: "none"});
	});

	/**
	 * 图片上传验证
	 * @param  {object} target file元素对象
	 */
	function filefujianChange(target) {
		var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
		var fileSize = 0;

		if (isIE && !target.files) {
			var filePath = target.value;
			var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
			var file = fileSystem.GetFile(filePath);
			fileSize = file.Size;
		}
		else {
			fileSize = target.files[0].size;
		}

		var size = fileSize / 1024;
		if(size > 10000) {
			window.pu_alert.show({
				title: "提示",
				content: "图片不能大于10MB",
				confirmText: '确认',
				alert: function() {
				},
				width: 400,
				height: 200
			});

			target.value="";
			return
		}

		var name = target.value;
		var fileName = name.substring(name.lastIndexOf(".")+1).toLowerCase();
		if(fileName !="jpg" && fileName !="jpeg" && fileName !="gif" && fileName !="png"){
			window.pu_alert.show({
				title: "提示",
				content: "请选择图片格式文件上传(jpg, jpeg, gif, png)！",
				confirmText: '确认',
				alert: function() {
				},
				width: 400,
				height: 200
			});

			target.value="";
			return;
		}
	}

	/**
	 * [currentTime 获取当前时间]
	 * @return {string} 返回年月日时分秒 例：20170519145725
	 */
	function currentTime() {
		var t = new Date();

		var year = t.getFullYear();
		var month = (t.getMonth() + 1) < 10 ?  ('0'+(t.getMonth() + 1)) : (t.getMonth() + 1);
		var date = t.getDate();
		var hours = t.getHours() < 10 ? '0' + t.getHours() : t.getHours();
		var min = t.getMinutes() < 10 ? '0' + t.getMinutes() : t.getMinutes();
		var sec = t.getSeconds() < 10 ? '0' + t.getSeconds() : t.getSeconds();

		return (year+''+month+''+date+''+hours+''+min+''+sec);

	}

	// 随机整数
	function rnd(start, end){
    	return Math.floor(Math.random() * (end - start) + start);
	}

	/**
	 * 商家随机编码
	 * @return {String} 商家随机编码 例：JDH1705191457259999
	 */
	function merchantCode() {
		var time = currentTime(); //当前时间，格式 20170519145725
		var t = ''+time.slice(2, 14); // 裁切时间 170519145725
		var random = ''+rnd(1000, 9999);
		var code = 'JDH'+ t + random;

		return code;
	}